﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ItemQuoteLibrary
{
    public class ItemQuoteEncoderBin:ItemQuoteEncoder
    {
        public Encoding EncodingType { get; private set; }

        public ItemQuoteEncoderBin(string encodingType)
        {
            EncodingType = Encoding.GetEncoding(encodingType);
        }

        public ItemQuoteEncoderBin()
            : this(ItemQuoteBinConst.DEFAULT_CHAR_ENC)
        {            
        }

        public byte[] Encode(ItemQuote item)
        {
            MemoryStream mem = new MemoryStream();
            BinaryWriter output = new BinaryWriter(new BufferedStream(mem));
            
            output.Write(IPAddress.HostToNetworkOrder(item.ItemNumber));
            output.Write(IPAddress.HostToNetworkOrder(item.Quantity));
            output.Write(IPAddress.HostToNetworkOrder(item.UnitPrice));
          
            byte flag = 0;

            if (item.Discounted)
                flag |= ItemQuoteBinConst.DISCOUNT_FLAG;
            if (item.InStock)
                flag |= ItemQuoteBinConst.IN_STOCK_FLAG;

            output.Write(flag);

            byte[] encodedDescription = EncodingType.GetBytes(item.ItemDescription);
            if (encodedDescription.Length > ItemQuoteBinConst.MAX_DESC_LEN)
                throw new IOException("Item description exceeds encoded length limit");
            output.Write((byte)encodedDescription.Length);
            output.Write(encodedDescription);

            output.Flush();

            return mem.ToArray();
        }
    }
}
